package parsers.calendar;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import parsers.CommonMethods;

import model.calendar.Calendar;
import model.calendar.MainCalendar;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

public class CalendarsParser
{	
	private MainCalendar mainCalendar;
	
	public CalendarsParser(MainCalendar mainCalendar) 
	{
		this.mainCalendar = mainCalendar;
	}
	
	public MainCalendar parse(boolean linkWithParent) throws IOException
	{
		MainCalendar mainCalendar = null;
		if(linkWithParent)
		{
			mainCalendar = this.mainCalendar;
		}
		else
		{
			mainCalendar = new MainCalendar(this.mainCalendar.getName(), this.mainCalendar.getDescription(), this.mainCalendar.getWarning(), this.mainCalendar.getShared());
			mainCalendar.setLink(CommonMethods.parseLink(this.mainCalendar.getLink()));
		}
		
		Source source = new Source(new URL(mainCalendar.getLink()));	
		List<Element> elements = source.getAllElements(HTMLElementName.CENTER);
		
		Calendar calendar = null;
		
		for (Element element : elements)
		{
			String name = element.getContent().toString();

			if(name.contains("<h3>") || name.contains("<H3>") || (name.contains("<b>") && !name.contains("Data"))|| (name.contains("<B>") && !name.contains("Data")))
			{
				name = CommonMethods.parseUnwantedMarkers(name);
				int br = 0;
				int cut = 0;
				
				if(name.contains("<br />"))
				{
					br = name.indexOf("<br />");
					cut = "<br />".length();
				}
				if(name.contains("<br>"))
				{
					br = name.indexOf("<br>");
					cut = "<br>".length();
				}
				
				if(br > 0)
				{
					name = name.substring(br + cut, name.length());
				}
				
				calendar = mainCalendar.createCalendar(name);
			}

			List<Element> e = element.getContent().getAllElements(HTMLElementName.TD);
			for (int i = 0; i < e.size(); i+=4)
			{
				String number = CommonMethods.parseUnwantedMarkers( e.get(i).getContent().toString() );
				String date = CommonMethods.parseUnwantedMarkers( e.get(i + 1).getContent().toString() );
				String dayP = CommonMethods.parseUnwantedMarkers( e.get(i + 2).getContent().toString() );
				String dayC = CommonMethods.parseUnwantedMarkers( e.get(i + 3).getContent().toString() );
				
				calendar.createEntry(number, date, dayP, dayC);
			}
		}

		return mainCalendar;
	}
	
	/*public static void main(String[] args) throws MalformedURLException, IOException
	{
		MainCalendar mc = new MainCalendar("", "", "", "");
		mc.setLink("http://plan.uz.zgora.pl/kalendarze_lista_szczegoly.php?pId_kalendarz=1303");
		
		CalendarsParser cp = new CalendarsParser(mc);
		MainCalendar newMC = cp.parse(false);
		System.out.println(newMC);
	}*/
}
